package org.springmole.business.bean;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlElementWrapper;


@XmlAccessorType(XmlAccessType.FIELD)
public class ResultStatus {
	
	@XmlAttribute
	private boolean success = false;
	
	@XmlElement(name="Message")
	private String message;
	
	@XmlElement(name="Description")
	private String description;

	@XmlElementWrapper(name="ErrorList")
	@XmlElement(name="Error")
	private List<ResultStatusError> resultStatusErrorList = new ArrayList<ResultStatusError>();
	
	
	public void parseException(Throwable throwable) {
		if (throwable instanceof SQLException) {
			for (Throwable sqlException : (SQLException)throwable) {
				resultStatusErrorList.add(createResultStatusError(sqlException));
			}
		} else {
			resultStatusErrorList.add(createResultStatusError(throwable));
		}

		setSuccess(false);
	}
	
	private ResultStatusError createResultStatusError(Throwable throwable) {
		ResultStatusError resultStatusError = new ResultStatusError();
		resultStatusError.setMessage(throwable.getMessage());
		
		StringWriter stringWriter = new StringWriter();
		PrintWriter printWriter = new PrintWriter(stringWriter);
		throwable.printStackTrace(printWriter);
		resultStatusError.setStackTrace(stringWriter.toString());
		
		return resultStatusError;
	}
	
	
	public boolean isSuccess() {
		return success;
	}
	public void setSuccess(boolean success) {
		this.success = success;
	}
	
	
	public String getMessage() {
		return message;
	}
	public void setMessage(String message) {
		this.message = message;
	}
	
	
	public String getDescription() {
		return description;
	}
	public void setDescription(String description) {
		this.description = description;
	}
	
	
	public List<ResultStatusError> getResultStatusErrorList() {
		return resultStatusErrorList;
	}
	public void setResultStatusErrorList(List<ResultStatusError> resultStatusErrorList) {
		this.resultStatusErrorList = resultStatusErrorList;
	}
}
